<template>
  <span class="countdown">倒计时：{{ remainingTime }}</span>
</template>
  
<script setup>
import { defineEmits,defineProps, ref, onMounted, onUnmounted,defineExpose, watch,onUpdated} from 'vue';

const props = defineProps({
  duration: {
    type: Number,
    required: true,
  },
  onFinish: {
    type: Function,
    default: () => {},
  },
});

const emit = defineEmits(['onFinish']);

const remainingTime = ref(props.duration);
const stopRef = ref(false);
const countdown = () => {
  if (remainingTime.value > 0) {
    remainingTime.value--;
    if (stopRef.value) {
      return
    }
    setTimeout(countdown, 1000);
  } else {
    emit('onFinish');
  }
};
const stopTimer = () => {
  stopRef.value = true;
};
const startTimer = () => {
  stopRef.value = false;
};
onUpdated(() => {
  // if (remainingTime.value !== props.duration) {
  //   remainingTime.value = props.duration;
  // }
});
watch(() => props.duration, () => {
  // remainingTime.value = props.duration;
  // countdown();
},{
  immediate: true
});

onMounted(() => {
  countdown();
});

onUnmounted(() => {
  clearTimeout(countdown);
});
defineExpose({
  stopTimer,
  startTimer,
  remainingTime,
  countdown,
})

</script>
 

  
  <style>
.countdown {
  /* 样式可以根据需要进行调整 */
}
</style>
  